/**
 * API 配置和基础请求封装
 * 提供统一的HTTP请求接口
 */

// API基础URL配置
const READ_API_BASE_URL = '/api'
const WRITE_API_BASE_URL = '/api'

/**
 * API响应数据结构
 */
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

/**
 * 用户登录请求参数
 */
export interface LoginRequest {
  userName: string
  password: string
}

/**
 * 用户注册请求参数
 */
export interface RegisterRequest {
  userName: string
  realName: string
  phone: string
  email: string
  password: string
  confirmPassword: string
}

/**
 * 用户信息响应数据
 */
export interface UserInfo {
  id: number
  userName: string
  realName: string
  phone: string
  email?: string
  createTime?: string
}

/**
 * 院区信息响应数据
 */
export interface HospitalArea {
  id: number
  name: string
  address: string
  phone?: string
  description?: string
  isSelfServiceEnabled: boolean
  tags: string[]
  longitude?: number
  latitude?: number
  sortOrder: number
  distance?: number
}

/**
 * 获取院区列表请求参数
 */
export interface GetHospitalAreasRequest {
  searchKeyword?: string
  userLongitude?: number
  userLatitude?: number
}

/**
 * HTTP请求方法枚举
 */
enum HttpMethod {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  DELETE = 'DELETE',
}

/**
 * 基础HTTP请求函数
 * @param url 请求URL
 * @param method HTTP方法
 * @param data 请求数据
 * @param headers 请求头
 * @param useWriteApi 是否使用写API
 * @returns Promise<ApiResponse<T>>
 */
async function request<T = any>(
  url: string,
  method: HttpMethod = HttpMethod.GET,
  data?: any,
  headers: Record<string, string> = {},
  useWriteApi: boolean = false,
): Promise<ApiResponse<T>> {
  try {
    const config: RequestInit = {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
    }

    // 如果是POST或PUT请求，添加请求体
    if ((method === HttpMethod.POST || method === HttpMethod.PUT) && data) {
      config.body = JSON.stringify(data)
    }

    // 根据操作类型选择API基础URL
    const baseUrl = useWriteApi ? WRITE_API_BASE_URL : READ_API_BASE_URL
    const response = await fetch(`${baseUrl}${url}`, config)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    return result
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

/**
 * API服务对象
 */
export const apiService = {
  /**
   * 用户登录
   * @param loginData 登录数据
   * @returns Promise<ApiResponse<UserInfo>>
   */
  async login(loginData: LoginRequest): Promise<ApiResponse<UserInfo>> {
    return request<UserInfo>('/User/login', HttpMethod.POST, loginData)
  },

  /**
   * 用户注册
   * @param registerData 注册数据
   * @returns Promise<ApiResponse<UserInfo>>
   */
  async register(registerData: RegisterRequest): Promise<ApiResponse<UserInfo>> {
    return request<UserInfo>('/User/register', HttpMethod.POST, registerData, {}, true)
  },

  /**
   * 获取用户信息
   * @param userId 用户ID
   * @returns Promise<ApiResponse<UserInfo>>
   */
  async getUserInfo(userId: number): Promise<ApiResponse<UserInfo>> {
    return request<UserInfo>(`/User/${userId}`, HttpMethod.GET)
  },

  /**
   * 获取自助开单院区列表
   * @param params 查询参数
   * @returns Promise<ApiResponse<HospitalArea[]>>
   */
  async getSelfServiceHospitalAreas(
    params?: GetHospitalAreasRequest,
  ): Promise<ApiResponse<HospitalArea[]>> {
    const queryParams = new URLSearchParams()
    if (params?.searchKeyword) {
      queryParams.append('searchKeyword', params.searchKeyword)
    }
    if (params?.userLongitude !== undefined) {
      queryParams.append('userLongitude', params.userLongitude.toString())
    }
    if (params?.userLatitude !== undefined) {
      queryParams.append('userLatitude', params.userLatitude.toString())
    }

    const queryString = queryParams.toString()
    const url = `/HospitalArea/self-service${queryString ? `?${queryString}` : ''}`
    return request<HospitalArea[]>(url, HttpMethod.GET)
  },

  /**
   * 获取所有院区列表
   * @param params 查询参数
   * @returns Promise<ApiResponse<HospitalArea[]>>
   */
  async getAllHospitalAreas(
    params?: GetHospitalAreasRequest,
  ): Promise<ApiResponse<HospitalArea[]>> {
    const queryParams = new URLSearchParams()
    if (params?.searchKeyword) {
      queryParams.append('searchKeyword', params.searchKeyword)
    }
    if (params?.userLongitude !== undefined) {
      queryParams.append('userLongitude', params.userLongitude.toString())
    }
    if (params?.userLatitude !== undefined) {
      queryParams.append('userLatitude', params.userLatitude.toString())
    }

    const queryString = queryParams.toString()
    const url = `/HospitalArea/all${queryString ? `?${queryString}` : ''}`
    return request<HospitalArea[]>(url, HttpMethod.GET)
  },

  /**
   * 根据ID获取院区详情
   * @param id 院区ID
   * @returns Promise<ApiResponse<HospitalArea>>
   */
  async getHospitalAreaById(id: number): Promise<ApiResponse<HospitalArea>> {
    return request<HospitalArea>(`/HospitalArea/${id}`, HttpMethod.GET)
  },

  /**
   * 提交开单申请
   * @param orderData 开单申请数据
   * @returns Promise<ApiResponse<any>>
   */
  async submitOrderApplication(
    orderData: SubmitOrderApplicationRequest,
  ): Promise<ApiResponse<any>> {
    return request<any>('/OrderApplication/submit', HttpMethod.POST, orderData, {}, true)
  },

  /**
   * 获取医疗项目列表
   * @param hospitalAreaId 院区ID
   * @param category 项目分类（可选）：0-检验项目，1-检查项目
   * @param onlyEnabled 是否只返回启用的项目，默认为true
   * @returns Promise<ApiResponse<ExaminationProject[]>>
   */
  async getExaminationProjects(
    hospitalAreaId: number,
    category?: number,
    onlyEnabled: boolean = true,
  ): Promise<ApiResponse<ExaminationProject[]>> {
    let url = `/MedicalProject?hospitalAreaId=${hospitalAreaId}&onlyEnabled=${onlyEnabled}`
    if (category !== undefined) {
      url += `&category=${category}`
    }
    return request<ExaminationProject[]>(url, HttpMethod.GET)
  },

  /**
   * 获取开单申请列表（分页）
   * @param params 查询参数
   * @returns Promise<ApiResponse<PagedResult<OrderApplicationDto>>>
   */
  async getOrderApplications(
    params: GetOrderApplicationsRequest,
  ): Promise<ApiResponse<PagedResult<OrderApplicationDto>>> {
    const queryParams = new URLSearchParams()

    if (params.userId !== undefined) {
      queryParams.append('userId', params.userId.toString())
    }
    if (params.hospitalAreaId !== undefined) {
      queryParams.append('hospitalAreaId', params.hospitalAreaId.toString())
    }
    if (params.status !== undefined) {
      queryParams.append('status', params.status.toString())
    }
    if (params.applicationNumber) {
      queryParams.append('applicationNumber', params.applicationNumber)
    }
    if (params.startDate) {
      queryParams.append('startDate', params.startDate)
    }
    if (params.endDate) {
      queryParams.append('endDate', params.endDate)
    }
    if (params.pageIndex !== undefined) {
      queryParams.append('pageIndex', params.pageIndex.toString())
    }
    if (params.pageSize !== undefined) {
      queryParams.append('pageSize', params.pageSize.toString())
    }
    if (params.sortField) {
      queryParams.append('sortField', params.sortField)
    }
    if (params.sortAscending !== undefined) {
      queryParams.append('sortAscending', params.sortAscending.toString())
    }

    const queryString = queryParams.toString()
    const url = `/OrderApplication${queryString ? `?${queryString}` : ''}`
    return request<PagedResult<OrderApplicationDto>>(url, HttpMethod.GET)
  },

  /**
   * 获取开单申请详情
   * @param id 申请ID
   * @param userId 用户ID（可选，用于权限验证）
   * @returns Promise<ApiResponse<OrderApplicationDetailDto>>
   */
  async getOrderApplicationDetail(
    id: number,
    userId?: number,
  ): Promise<ApiResponse<OrderApplicationDetailDto>> {
    let url = `/OrderApplication/${id}`
    if (userId !== undefined) {
      url += `?userId=${userId}`
    }
    return request<OrderApplicationDetailDto>(url, HttpMethod.GET)
  },

  /**
   * 支付开单申请
   * @param paymentData 支付数据
   * @returns Promise<ApiResponse<PaymentResultDto>>
   */
  async payOrderApplication(
    paymentData: PayOrderApplicationRequest,
  ): Promise<ApiResponse<PaymentResultDto>> {
    return request<PaymentResultDto>(
      '/OrderApplication/pay',
      HttpMethod.POST,
      paymentData,
      {},
      true,
    )
  },
}

/**
 * 开单申请项目接口
 * 匹配后端 OrderApplicationItemDto 结构
 */
export interface OrderApplicationItem {
  medicalProjectId: number // 医疗项目ID
  quantity: number // 项目数量
}

/**
 * 提交开单申请请求参数
 */
export interface SubmitOrderApplicationRequest {
  userId: number
  hospitalAreaId: number
  items: OrderApplicationItem[]
  contactPhone: string
  remarks?: string
}

/**
 * 医疗项目接口（对应后端MedicalProjectDto）
 */
export interface ExaminationProject {
  id: number
  name: string
  description?: string
  price: number
  category: number // 0-检验项目，1-检查项目
  code: string
  tags?: string
  estimatedDuration?: number // 预计时长（分钟）
  preparationInstructions?: string // 检查前准备说明
  sortOrder: number
}

/**
 * 分页结果接口
 */
export interface PagedResult<T> {
  items: T[]
  totalCount: number
  pageIndex: number
  pageSize: number
  totalPages: number
}

/**
 * 获取开单申请列表请求参数
 */
export interface GetOrderApplicationsRequest {
  userId?: number
  hospitalAreaId?: number
  status?: OrderApplicationStatus
  applicationNumber?: string
  startDate?: string
  endDate?: string
  pageIndex?: number
  pageSize?: number
  sortField?: string
  sortAscending?: boolean
}

/**
 * 开单申请状态枚举
 */
export enum OrderApplicationStatus {
  Draft = 0, // 草稿
  Submitted = 1, // 已提交
  Paid = 2, // 已支付
  Progress = 3, // 进行中
  Completed = 4, // 已完成
  Cancelled = 5, // 已取消
}

/**
 * 开单申请数据传输对象
 */
export interface OrderApplicationDto {
  id: number
  applicationNumber: string
  userId: number
  userName: string
  hospitalAreaId: number
  hospitalAreaName: string
  status: OrderApplicationStatus
  statusDescription: string
  projectCount: number
  totalAmount: number
  remarks?: string
  appointmentDate?: string
  appointmentTimeSlot?: string
  contactPhone: string
  createTime: string
  updateTime: string
}

/**
 * 开单申请详情数据传输对象
 */
export interface OrderApplicationDetailDto {
  id: number
  applicationNumber: string
  userId: number
  userName: string
  hospitalAreaId: number
  hospitalAreaName: string
  status: OrderApplicationStatus
  statusDescription: string
  totalAmount: number
  remarks?: string
  appointmentDate?: string
  appointmentTimeSlot?: string
  contactPhone: string
  createTime: string
  updateTime: string
  items: OrderApplicationItemDetailDto[]
}

/**
 * 开单申请项目详情数据传输对象
 */
export interface OrderApplicationItemDetailDto {
  id: number
  medicalProjectId: number
  projectName: string
  projectPrice: number
  projectDescription?: string
  projectCategory: number
  projectCode?: string
  quantity: number
  subTotal: number
  estimatedDuration?: number
  preparationInstructions?: string
}

/**
 * 支付开单申请请求数据
 */
export interface PayOrderApplicationRequest {
  orderApplicationId: number
  userId: number
  paymentMethod: string
  paymentAmount: number
  paymentTransactionId?: string
}

/**
 * 支付结果数据传输对象
 */
export interface PaymentResultDto {
  orderApplicationId: number
  applicationNumber: string
  paymentSuccess: boolean
  paymentTime: string
  paymentAmount: number
  paymentMethod: string
  paymentTransactionId?: string
  status: OrderApplicationStatus
}

export default apiService
